/**
 * Copyright (C) 2011 - @le.nguyen
 * @Created Jul 28, 2011
 *
 * TODO
 */
package com.conan.dailyflickr.activity;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Random;

import javax.crypto.spec.PSource;

import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Toast;

import com.conan.dailyflickr.R;

/**  */
public class DowloadedPhotos extends Activity{
	private final String TAG = "DowloadedPhotos";
	private Gallery gallery;
	private ImageView imgView;
	
	// private Cursor mImageCursor = null;
	// private Cursor mThumbsCursor = null;
	String[] projection = { MediaStore.Images.ImageColumns._ID,
            MediaStore.Images.ImageColumns.DATA};
	String[] projection_thumbs = { MediaStore.Images.Thumbnails._ID,};
    int mProjection_Id                  = 0;
    int mProjection_Data                = 1;
    int mProjection_thumb_Id            = 0;
    int mProjection_thumb_imgId         = 1;
    
	private final String DOWNLOAD_FOLDER_FILTER = "/download";

	@Override
	protected void onCreate(Bundle savedInstanceState) {	
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		imgView = (ImageView)findViewById(R.id.ImageView);
		gallery = (Gallery) findViewById(R.id.gallery);
		gallery.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView parent, View v, int position, long id) {
            	ImageData data = mImages.get(position);
            	Bitmap newBitmap = BitmapFactory.decodeFile( data._url, null );
                if(newBitmap != null){
                	imgView.setImageBitmap(newBitmap);
                }else{
                	imgView.setImageResource(R.drawable.no_image);
                }
                
                if(mainBitmap != null){
                	mainBitmap.recycle();
                }
                mainBitmap = newBitmap;
                
            }
        });
		
		
		// Query for all images on external storage	    
		init_data();
		Toast.makeText(this, "mImage = " + mImages.size() , 0);
	}	
	
	Bitmap mainBitmap = null;
	private void init_data(){
	   String filter =  MediaStore.MediaColumns.DATA + " like '%" + DOWNLOAD_FOLDER_FILTER + "/%'";  
		   
	   // filter = "(" + filter + ") AND " + getMediaTypeFilter();
	   
	   Cursor mImageCursor = null;
       try {
    	   mImageCursor = getContentResolver().query(
    		   MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, 
               filter , null, null);
       } catch (android.database.sqlite.SQLiteMisuseException e) {
           Log.e(TAG, ">>> SQLite error: " + e.toString());
       } catch (android.database.sqlite.SQLiteException e) {
           Log.e(TAG, ">>> SQLite error: " + e.toString());
       }
       
	    // Initialize an adapter to display images in grid
       Cursor cursor = null;
       int columnIndex = 0;
	    if ( mImageCursor != null ) {
	    	Log.e(TAG, "mImageCursor.count --> " + mImageCursor.getCount());
	    	 if (mImageCursor.moveToFirst() == true) {
	    		 for (;;) {
	    			 ImageData data = new ImageData();
	    			 data._imageID = mImageCursor.getInt(mProjection_Id);
	    			 data._url = mImageCursor.getString(mProjection_Data);
	    			 
	    			 filter = MediaStore.Images.Thumbnails.IMAGE_ID + " = " + data._imageID;
	    			 cursor = managedQuery( MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
                             projection_thumbs, filter, null, null );

					 if(cursor != null && cursor.moveToFirst() == true){
						 columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
						 data._thumbID = cursor.getInt(columnIndex);
						 cursor.close();
					 }
	    			 
					 Log.e(TAG, "mImageCursor.moveToNext() --> " + data._url);
	    			 mImages.add(data);
	    			 if(!mImageCursor.moveToNext()) break;
	    		 }
	        
	    	 }
	    	 
	    	mImageCursor.close();
	    	
	        ImageAdapter mAdapter = new ImageAdapter(this);
	        gallery.setAdapter(mAdapter);
	        
	        Random ran = new Random();
	        int position = ran.nextInt(mImages.size());
	        
	        gallery.setSelection(position, true);
	        ImageData data = mImages.get(position);
        	Bitmap newBitmap = BitmapFactory.decodeFile( data._url, null );
            if(newBitmap != null){
            	imgView.setImageBitmap(newBitmap);
            }else{
            	imgView.setImageResource(R.drawable.no_image);
            }
	    }		
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}
	
	protected Bitmap loadThumbnailImage( String url ) {
	    // Get original image ID
	    int originalImageId = Integer.parseInt(url.substring(url.lastIndexOf("/") + 1, url.length()));

	    // Get (or create upon demand) the micro thumbnail for the original image.
	    return MediaStore.Images.Thumbnails.getThumbnail(this.getContentResolver(),
	                        originalImageId, MediaStore.Images.Thumbnails.MINI_KIND, null);
	}

	ArrayList<ImageData> mImages = new ArrayList<ImageData>();
	
	/***************************************************************************************************
	 *************************************************************************************************** 
	 ***************************************************************************************************/
	int GalItemBg;
	public class ImageAdapter extends BaseAdapter {
        int GalItemBg;
        private Context cont;

        public ImageAdapter(Context c) {
            cont = c;
            TypedArray typArray = obtainStyledAttributes(R.styleable.GalleryTheme);
            GalItemBg = typArray.getResourceId(R.styleable.GalleryTheme_android_galleryItemBackground, 0);
            typArray.recycle();
        }

        public int getCount() {
            return mImages.size();
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView imgView = new ImageView(cont);

//            Bitmap bm = loadThumbnailImage(images.get(position));
//            if(bm != null){
//            	imgView.setImageBitmap(bm);
//            }else{
//            	imgView.setImageResource(R.drawable.no_image);
//            }
            
            ImageData data = mImages.get(position);
            if(data._thumbID < 0){
            	imgView.setImageResource(R.drawable.no_image);
            }else{
                imgView.setImageURI(Uri.withAppendedPath(
                        MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, "" + data._thumbID));
            }
            
            imgView.setLayoutParams(new Gallery.LayoutParams(125, 110));
            imgView.setScaleType(ImageView.ScaleType.FIT_XY);
            imgView.setBackgroundResource(GalItemBg);

            return imgView;
        }
    }
	

	private String getMediaTypeFilter(){
		return "((LOWER(mime_type) = 'image/jpeg') OR ( LOWER("
        + Images.Media.MIME_TYPE + ") = 'image/jpg') OR ( LOWER("
        + Images.Media.MIME_TYPE + ") = 'image/png') OR ( LOWER(" 
        + Images.Media.MIME_TYPE + ") = 'image/bmp') OR ( LOWER("
        + Images.Media.MIME_TYPE + ") = 'image/gif') OR ( LOWER("
        + Images.Media.MIME_TYPE + ") = 'image/vnd.wap.wbmp') OR ( LOWER("
        + Images.Media.MIME_TYPE + ") = 'image/x-ms-bmp'))"
        + " AND " 
            + " (" + Images.Media.SIZE + "> 0)  "
        +" AND (NOT ( LOWER("
            + Images.Media.DISPLAY_NAME +") = 'front.jpg'))"
        +" AND (NOT ( LOWER("
            + Images.Media.DISPLAY_NAME +") = 'back.jpg'))"
        +" AND (NOT "                    
            + Images.Media.DISPLAY_NAME +" LIKE 'Cover.jpg')"
        +" AND (NOT "                    
            + Images.Media.DISPLAY_NAME +" LIKE 'CD.jpg')";
	}
	
	private class ImageData{
		public ImageData() {
			_thumbID = -1;
		}
		int _thumbID;
		int _imageID;
		String _url;
	}
}
